<?php
namespace app\api\controller;

use app\home\model\Demand as ModelDemand;
use app\home\model\ShortLink;
use think\facade\Db;

class Demand
{
    public function index()
    { 
        $page = ( request()->param('page') - 1 ) * 10;
        $sql = "SELECT id FROM stpc_qzz_demand ORDER BY add_time DESC LIMIT $page, 1";
        $last_demand_id = Db::query($sql)[0]['id'];
        $demands = ModelDemand::where('id', '<=', $last_demand_id)->where('title', '<>', '')->order('id desc')->limit(0, 10)->select();
        return json([
            'status'=>200,
            'demands'=>$demands,
            'last_id'=>$last_demand_id,
            'count'=>ModelDemand::count(),
        ]);
    }
    public function add()
    {
        $data = request()->param();
        unset($data['add_time'], $data['update_time']);
        $data['hash_str'] = get_hash();
        $demand = new ModelDemand();
        $demand->save($data);
        $id = $demand->id;
        unset($demand);
        $st = new ShortLink;
        $st->save([
            'c_name'=>'Dd',
            'p_name'=>'page',
            'p_id'=>$id,
            'hash_str'=>$data['hash_str']
        ]);
        $demand = ModelDemand::find($id);
        
        return json([
            'demand'=>$demand
        ]);

    }
    public function edit()
    {
        $data = request()->param();
        if ($data['rec']){
            $data['rec'] = 1;
        }else{
            $data['rec'] = 0;
        }
        unset($data['add_time'], $data['update_time']);
        $demand = ModelDemand::find($data['id']);
        $demand->save($data);
        unset($demand);
        $demand = ModelDemand::find($data['id']);
        return json([
            'demand'=>$demand
        ]);
    }
    public function del()
    {
        $id = request()->param('id');
        $demand = ModelDemand::find($id);
        $hash = $demand['hash_str'];
        ShortLink::where('hash_str', $hash)->delete();
        ModelDemand::destroy($id);
    }
    public function getDemand()
    {
        $id = request()->param('id');
        return json([
            'demand'=>ModelDemand::find($id),
        ]);
    }
}
